<!--
 * @页面名称:顶部url借阅清单
 * @描述: 
 * @作者: 
 * @Date:
-->
<template>
  <div class="urlBorrow">
    <el-tooltip class="box-item" effect="dark" placement="top" content="Url借阅">
      <el-badge v-if="fileCount > 0" :value="fileCount" class="item">
        <el-icon style="font-size: 22px; cursor: pointer" @click="showModal"><ShoppingCart /></el-icon>
      </el-badge>
      <el-icon v-else style="font-size: 22px; cursor: pointer" @click="showModal"><ShoppingCart /></el-icon>
    </el-tooltip>
    <!-- 借阅清单弹框 -->
    <el-dialog v-model="modalSetting.visible" :title="modalSetting.title" width="1000" draggable>
      <el-tabs v-model="activeName" class="demo-tabs" @tab-change="tabChange">
        <el-tab-pane label="目录清单" name="1">
          <splitpanes :dbl-click-splitter="false" horizontal style="display: flex; height: 100%; background-color: #ffffff">
            <pane>
              <stable :columns="tableSetting.columns" :data="tableSetting.data" @rowClick="rowClick"></stable>
            </pane>
            <pane>
              <stable :columns="tableSetting.columns2" :data="tableSetting.data2"></stable>
            </pane>
          </splitpanes>
        </el-tab-pane>
        <el-tab-pane label="全文清单" name="2">
          <div style="height: 100%">
            <stable :columns="tableSetting2.columns" :data="tableSetting2.data"></stable>
          </div>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="danger" @click="clearData">清空数据</el-button>
          <el-button @click="modalSetting.visible = false">取消</el-button>
          <el-button v-if="activeName === '1'" type="primary" @click="ok" disabled>申请借阅</el-button>
          <el-button v-else type="primary" @click="ok2">外链借阅</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- url借阅弹框 -->
    <modal v-model:visible="urlModal.isShow" :title="urlModal.title" width="1000" @ok="urlBorrow">
      <el-form :model="urlFormModal" label-width="100px" ref="urlFormRef" :rules="rules">
        <el-form-item label="外链地址:">
          <el-input v-model="urlFormModal.url" disabled />
        </el-form-item>
        <el-row>
          <el-col :span="6">
            <el-form-item label="是否打印:">
              <el-checkbox v-model="urlFormModal.isPrint"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否下载:">
              <el-checkbox v-model="urlFormModal.isDownload"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="启用:">
              <el-checkbox v-model="urlFormModal.enable"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="验证码启用:">
              <el-checkbox v-model="urlFormModal.code_enable"></el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="验证码:">
              <el-input v-model="urlFormModal.code"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="水印文字:">
              <el-input v-model="urlFormModal.watermark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="指定借阅人:">
              <el-input v-model="urlFormModal.borrower" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="借阅日期:" prop="borrowDate">
              <el-date-picker v-model="urlFormModal.borrowDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择日期" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="到期时间:">
              <el-date-picker v-model="urlFormModal.expireDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择日期" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="备注:" prop="remark">
              <el-input v-model="urlFormModal.remark" :rows="2" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
        <stable height="280px" :columns="tableSetting2.columns" :data="tableSetting2.data"></stable>
      </el-form>
    </modal>
  </div>
</template>

<script setup lang="tsx">
import { reactive, ref, nextTick, onMounted, computed } from "vue";
import { useDictionryStore } from "@/stores/modules/dictionary";
import { useUserStore } from "@/stores/modules/user";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { fileSizeFormat } from "@/utils/formatter";
import { getSysConfig } from "@/utils/util";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import ACrypto from "@/utils/crypto";
import dtime from "moment";

const { proxy } = useCurrentInstance();
// tab页绑定字段
const activeName = ref("1");
// 借阅清单弹框配置
const modalSetting = reactive({
  visible: false,
  title: "借阅清单"
});
// url弹框配置
const urlModal = reactive({
  isShow: false,
  title: "电子文件借阅"
});
// 表单绑定字段
const urlFormModal = ref({
  url: "", //传到数据库的url
  url2: "", //页面显示的url
  isPrint: false,
  isDownload: false,
  enable: true,
  code: "",
  watermark: "",
  borrower: "",
  borrowDate: "",
  expireDate: "",
  remark: "",
  deptName: "",
  code_enable: true
});
// 表单规则
const rules = reactive({
  borrowDate: [{ required: true, message: "请选择借阅日期", trigger: "change" }]
});
// 表单实例
const urlFormRef = ref();
// url预览地址随机key
const key = ref("");
// 借阅车右上角图标数量
const fileCount = computed(() => {
  return userStore.fileCount;
});
// pinia数据
const dictionryStore = useDictionryStore();

const userStore = useUserStore();
// 表格数据初始化
const formatter = ({ row, column, cellValue }: any) => {
  // 保管期限
  if (column.property === "RetentionPeriod") {
    const BGQX = dictionryStore.getDictionaryObj["BGQXdata"];
    const data = BGQX.find((v: any) => v.DDL_ID === cellValue);
    return data ? data.DDL_Name : "";
  }
  if (column.property === "Title") {
    cellValue = ACrypto.getSS(row[column.property]);
  }
  return cellValue;
};
// 目录清单表格配置
const tableSetting = reactive({
  // 目录清单中业务数据表头
  columns: [
    { field: "Year", title: "年度", width: 90, sortable: true },
    { field: "Title", title: "题名", sortable: true, formatter: formatter },
    { field: "Collect_Create_DateTime", title: "归档时间", width: 150, sortable: true },
    { field: "Code", title: "档号", width: 150, sortable: true },
    { field: "RetentionPeriod", title: "保管期限", width: 150, sortable: true, formatter: formatter },
    {
      title: "操作",
      width: 80,
      fixed: "right",
      slots: {
        default: ({ row, rowIndex }: any) => {
          return [
            <el-link underline={false} type="primary" onClick={() => deleteDoListData(row)}>
              移除
            </el-link>
          ];
        }
      }
    }
  ],
  // 目录清单中全文数据表头
  columns2: [
    { field: "AI_Index", title: "顺序号", width: 90, sortable: true },
    { field: "AI_Name", title: "文件名", sortable: true },
    { field: "AI_Source_Size", title: "文件大小", width: 150, sortable: true, formatter: fileSizeFormat },
    { field: "AI_UploadDateTime", title: "上传时间", width: 150, sortable: true },
    { field: "AI_FileDateTime", title: "创建时间", width: 150, sortable: true },
    {
      title: "操作",
      width: 80,
      fixed: "right",
      slots: {
        default: ({ row, rowIndex }: any) => {
          return [
            <el-link underline={false} type="primary" onClick={() => deleteFulltext(row)}>
              移除
            </el-link>
          ];
        }
      }
    }
  ],
  // 目录清单中业务数据单击保存对象
  rowClickObj: {} as any,
  // 目录清单中业务数据
  data: [],
  // 目录清单中全文数据
  data2: []
});
// 全文清单表格配置
const tableSetting2 = reactive({
  columns: [
    { field: "AI_Index", title: "顺序号", width: 90, sortable: true },
    { field: "AI_Name", title: "文件名", sortable: true },
    { field: "AI_Source_Size", title: "文件大小", width: 150, sortable: true, formatter: fileSizeFormat },
    { field: "AI_UploadDateTime", title: "上传时间", width: 150, sortable: true },
    { field: "AI_FileDateTime", title: "创建时间", width: 150, sortable: true },
    {
      title: "操作",
      width: 80,
      fixed: "right",
      slots: {
        default: ({ row, rowIndex }: any) => {
          return [
            <el-link underline={false} type="primary" onClick={() => deleteFulltext(row)}>
              移除
            </el-link>
          ];
        }
      }
    }
  ],
  data: [] as any[]
});
// 显示弹窗
const showModal = () => {
  modalSetting.visible = true;
  getData();
  getFullTextInfos();
};
// 切换tab页
const tabChange = (name: any) => {
  activeName.value = name;
};
// 获取数据
const getData = () => {
  proxy.$vueAxios.get("MasterBaseBorrow/Get").then((res: any) => {
    tableSetting.data = res.List;
    tableSetting.data2 = [];
  });
};
// 业务数据单击事件
const rowClick = ({ row }: any) => {
  tableSetting.rowClickObj = row;
  getDoListAllInfos();
};
// 获取目录清单下的全文
const getDoListAllInfos = () => {
  proxy.$vueAxios
    .get("MasterBaseBorrow/GetTemporaryAllInfos", { recordId: tableSetting.rowClickObj.Record_ID })
    .then((res: any) => {
      tableSetting.data2 = res.List;
    });
};
// 获取全文清单下的全文
const getFullTextInfos = () => {
  proxy.$vueAxios.get("MasterBaseBorrow/GetAllTemporaryAllInfos").then((res: any) => {
    tableSetting2.data = res.List;
  });
};
// 删除目录清单数据
const deleteDoListData = (row: any) => {
  proxy.$vueAxios.post("MasterBaseBorrow/DeleteTemporaryData", [row.Record_ID]).then((res: any) => {
    if (res.Mark) {
      proxy.$message.success("删除成功!");
      proxy.$vueAxios.get("MasterBaseBorrow/Get").then((res: any) => {
        if (res.Mark) {
          userStore.setFileCount(res.Count);
        }
      });
      getData();
    } else {
      proxy.$message.error("删除失败!");
    }
  });
};
// 删除全文数据
const deleteFulltext = (row: any) => {
  proxy.$vueAxios
    .post("MasterBaseBorrow/DeleteTemporaryDataAllInfos", { recordId: row.Record_ID, aiID: row.AI_ID })
    .then((res: any) => {
      if (res.Mark) {
        proxy.$message.success("删除成功!");
        activeName.value == "1" ? getDoListAllInfos() : getFullTextInfos();
      } else {
        proxy.$message.error("删除失败!");
      }
    });
};
// 清空数据
const clearData = () => {
  proxy.$vueAxios.post("MasterBaseBorrow/EmptyTemporaryData").then((res: any) => {
    if (res.Mark) {
      proxy.$message.success("清空成功!");
      tableSetting.data = [];
      tableSetting.data2 = [];
      tableSetting2.data = [];
      userStore.setFileCount(0);
    } else {
      proxy.$message.error("清空失败!");
    }
  });
};
// 点击申请借阅按钮
const ok = () => {};
// 点击url借阅按钮
const ok2 = () => {
  modalSetting.visible = false;
  urlModal.isShow = true;
  const PreviewUrl = getSysConfig("PreviewUrl");
  nextTick(() => {
    if (urlFormRef.value) {
      urlFormRef.value.resetFields();
    }
    key.value = proxy.$global.createID();
    urlFormModal.value.code = createCode();
    urlFormModal.value.enable = true;
    urlFormModal.value.borrowDate = dtime().format("YYYY-MM-DD");
    urlFormModal.value.url = `${PreviewUrl}/#/preview?key=${key.value}`;
    urlFormModal.value.url2 = `/#/preview?key=${key.value}`;
  });
};
// 生成随机验证码
const createCode = () => {
  let code = "";
  const codeLength = 6; // 验证码的长度
  const random = [
    0,
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    "A",
    "B",
    "C",
    "D",
    "E",
    "F",
    "G",
    "H",
    "I",
    "J",
    "K",
    "L",
    "M",
    "N",
    "O",
    "P",
    "Q",
    "R",
    "S",
    "T",
    "U",
    "V",
    "W",
    "X",
    "Y",
    "Z"
  ]; // 随机数
  for (let i = 0; i < codeLength; i++) {
    // 循环操作
    const index = Math.floor(Math.random() * 36); // 取得随机数的索引（0~35）
    code += random[index]; // 根据索引取得随机数加到code上
  }
  return code;
};
// url借阅确定事件
const urlBorrow = () => {
  urlFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const params = {
        bU_ID: key.value,
        secondID: tableSetting2.data[0].AI_ID,
        fonds_ID: userStore.userInfo.Fonds_ID,
        bU_BorrowDate: urlFormModal.value.borrowDate,
        bU_ExpireDate: urlFormModal.value.expireDate,
        bU_IsPrint: urlFormModal.value.isPrint,
        bU_IsDownload: urlFormModal.value.isDownload,
        bU_WaterMark: urlFormModal.value.watermark,
        bU_DeptName: urlFormModal.value.deptName,
        bU_BorrowUser: urlFormModal.value.borrower,
        bU_PreviewUrl: urlFormModal.value.url2,
        bU_Verification_Code: urlFormModal.value.code,
        bU_Enable_Verification_Code: urlFormModal.value.code_enable,
        bU_Remark: urlFormModal.value.remark,
        bU_IsEnable: urlFormModal.value.enable,
        fileInfos: tableSetting2.data.map((v: any) => v.AI_ID)
      };
      proxy.$vueAxios.post("MasterBaseBorrowUrl/Add", params, { noLoading: true }).then((res: any) => {
        if (res.Mark) {
          proxy.$message.success("添加成功");
          urlModal.isShow = false;
          clearData();
        }
      });
    }
  });
};
onMounted(() => {
  proxy.$vueAxios.get("MasterBaseBorrow/Get").then((res: any) => {
    if (res.Mark) {
      userStore.setFileCount(res.Count);
    }
  });
});
</script>

<style scoped lang="scss">
:deep(.el-dialog__body) {
  height: 500px;
}
.el-tabs {
  height: 100%;
  :deep(.el-tabs__content) {
    height: calc(100% - 52px);
    .el-tab-pane {
      height: 100%;
    }
  }
}
:deep(.el-date-editor--date) {
  width: 100%;
}
:deep(.el-input__wrapper) {
  width: calc(100% - 22px);
}
</style>
